/**
 * 
 */
package pl.kane.autokomp.applications.actionlisteners.file;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JFileChooser;

import pl.kane.autokomp.Template;
import pl.kane.autokomp.applications.MainFrame;

/**
 * @author Lukasz Wator
 *
 */
public class OpenAction implements ActionListener {
	 
	public void actionPerformed(ActionEvent arg0) {
		final MainFrame mainFrame = MainFrame.getInstance() ;
		JFileChooser fc = new JFileChooser();
    	fc.setCurrentDirectory(new File("."));
    	int returnVal = fc.showOpenDialog(mainFrame.getFrame());
    	if (returnVal == JFileChooser.APPROVE_OPTION) {
    		 File file = fc.getSelectedFile();
    		 FileReader fr;
			try {
				fr = new FileReader(file);
				BufferedReader br = new BufferedReader(fr);
				StringBuffer code = new StringBuffer();
				String line;
				while ((line = br.readLine()) != null) { // while loop begins here
					code.append(line+"\n");
			       }
				 mainFrame.setCode(code.toString());
	    		 mainFrame.addToConsole("File "+file.getName()+" opened\n");
	    		 mainFrame.setCurrentFileName(file.getName());
	    		 
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
 			 
    	} else {
    		 mainFrame.addToConsole("File open canceled\n");
        }

       
     }

}
